package com.example.activity;

import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import com.example.R;
import com.example.download.HttpDownloader;
import com.example.download.XmlDownloader;
import com.example.modle.Mp3Info;
import com.example.services.Mp3DownLoadServices;
import com.example.util.LoggerUtil;
import com.example.xml.Mp3ListXmlHandler;

public class RemoteResourceActivity extends AResourceActivity {

    // 菜单刷新id
    public static final int REFRESH_ID = 1;

    // 菜单关于id
    public static final int ABOUT_ID = 2;

    private List<Mp3Info> infos;

    /**
     * 注意了，127.0.0.1（localhost）并不是直接连本机的tomcat地址，所以一直提示连接拒绝错误，
     * 该改成：10.0.2.2
     */
    // resource xml的url地址
//    public static final String URI = "http://10.0.2.2:8080/mp3/resource.xml";
    public static final String URI = "http://132.96.63.41:8080/mp3/resource.xml";

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remoteresourcelayout);

        super.updateListView();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        Mp3Info mp3 = this.infos.get(position);

        Intent intent = new Intent();
        intent.setClass(this, Mp3DownLoadServices.class);
        intent.putExtra("mp3", mp3);
        super.startService(intent);

        super.onListItemClick(l, v, position, id);
    }

    @Override
    protected List<Mp3Info> getMp3Infos() {

        String xml = downloadXml(URI);
        System.out.println(xml);

//        byte[] xml_utf8 = StringUtil.gbk2utf8(xml);
//        try {
//            xml = new String(xml_utf8, 0, xml_utf8.length, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//        }
//
//        System.out.println(xml);

        this.infos = pasre(xml);
        return this.infos;
    }

    /**
     * 下载xml文件（描述文件)
     *
     * @param url
     *
     * @return
     */
    private String downloadXml(String url) {
        HttpDownloader downloader = new XmlDownloader();

        byte[] resourcConfigByte = downloader.downLoad(url);
        String resourceContent = null;
        try {
            resourceContent = new String(resourcConfigByte, 0, resourcConfigByte.length, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

//        String resourceContent = downloader.download(url);

        return resourceContent;
    }

    private List<Mp3Info> pasre(String xml) {

        SAXParserFactory factory = SAXParserFactory.newInstance();
        List<Mp3Info> infos = new ArrayList<Mp3Info>();

        try {
            XMLReader reader = factory.newSAXParser().getXMLReader();
            Mp3ListXmlHandler handler = new Mp3ListXmlHandler(infos);

            reader.setContentHandler(handler);
            InputSource in = new InputSource(new StringReader(xml));
            reader.parse(in);

            for (Iterator iterator = infos.iterator(); iterator.hasNext(); ) {
                Mp3Info mp3Info = (Mp3Info) iterator.next();
                LoggerUtil.info(this.getClass(), "----------" + mp3Info.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return infos;
    }

//    /**
//     * 点击菜单的时候，将会调用此方法，创建两个按扭
//     *
//     * @param menu
//     * @return
//     */
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//
//
//        menu.add(0, REFRESH_ID, 1, R.string.Menu_Refresh);
//        menu.add(0, ABOUT_ID, 1, R.string.Menu_About);
//
//        return super.onCreateOptionsMenu(menu);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//
//        System.out.println("Item id is [" + item.getItemId() + "]");
//
//        switch (item.getItemId()) {
//
//            /**
//             * 需要更新xml
//             */
//            case REFRESH_ID: {
//
//                updateListView();
//                break;
//            }
//
//            /**
//             * 显示信息
//             */
//            case ABOUT_ID: {
//
//                System.out.println("显示关于信息");
//                Toast.makeText(this,"显示关于信息",10);
//                break;
//            }
//        }
//        return super.onOptionsItemSelected(item);
//    }
}
